<template>
	<gradient-background>
		<custom-navbar :title="'个人中心'"></custom-navbar>
		
		<view class="container">
			<view class="content">
				<!-- 用户信息 -->
				<view class="user-section" @tap="handleUserClick">
					<user-avatar 
						:size="large"
						:userInfo="userInfo"
					></user-avatar>
					<view class="user-info">
						<text class="user-name">{{ displayName }}</text>
						<text class="user-desc">{{ displayDesc }}</text>
						<view class="login-hint" v-if="!isLoggedIn">
							<text class="hint-text">点击登录 →</text>
						</view>
					</view>
				</view>
				
				<!-- 统计信息 -->
				<view class="stats-section">
					<view class="stats-grid">
						<view class="stats-item">
							<text class="stats-number">{{ totalDivinations }}</text>
							<text class="stats-label">总占卜次数</text>
						</view>
						<view class="stats-item">
							<text class="stats-number">{{ totalDays }}</text>
							<text class="stats-label">使用天数</text>
						</view>
						<view class="stats-item">
							<text class="stats-number">{{ favoriteHexagram }}</text>
							<text class="stats-label">最常见卦象</text>
						</view>
					</view>
				</view>
				
				<!-- 功能菜单 -->
				<view class="menu-section">
					<view class="menu-item" @tap="editProfile" v-if="isLoggedIn">
						<view class="menu-icon">👤</view>
						<text class="menu-title">编辑资料</text>
						<view class="menu-arrow">→</view>
					</view>
					
					<view class="menu-item" @tap="viewMyRecords">
						<view class="menu-icon">📋</view>
						<text class="menu-title">我的记录</text>
						<view class="menu-arrow">→</view>
					</view>
					
					<view class="menu-item" @tap="viewFavorites">
						<view class="menu-icon">⭐</view>
						<text class="menu-title">收藏卦象</text>
						<view class="menu-arrow">→</view>
					</view>
					
					<view class="menu-item" @tap="openSettings">
						<view class="menu-icon">⚙️</view>
						<text class="menu-title">设置</text>
						<view class="menu-arrow">→</view>
					</view>
					
					<view class="menu-item" @tap="openHelp">
						<view class="menu-icon">❓</view>
						<text class="menu-title">帮助与反馈</text>
						<view class="menu-arrow">→</view>
					</view>
					
					<view class="menu-item" @tap="openAbout">
						<view class="menu-icon">ℹ️</view>
						<text class="menu-title">关于我们</text>
						<view class="menu-arrow">→</view>
					</view>
					
					<view class="menu-item logout-item" @tap="logout" v-if="isLoggedIn">
						<view class="menu-icon">🚪</view>
						<text class="menu-title">退出登录</text>
						<view class="menu-arrow">→</view>
					</view>
				</view>
				
				<!-- 今日推荐 -->
				<view class="recommendation-section">
					<view class="section-title">今日推荐</view>
					<view class="recommendation-card" @tap="viewRecommendation">
						<view class="recommendation-content">
							<text class="recommendation-title">{{ recommendationTitle }}</text>
							<text class="recommendation-desc">{{ recommendationDesc }}</text>
						</view>
						<view class="recommendation-icon">🌟</view>
					</view>
				</view>
			</view>
		</view>
	</gradient-background>
</template>

<script>
import GradientBackground from '@/components/gradient-background/gradient-background.vue'
import CustomNavbar from '@/components/custom-navbar/custom-navbar.vue'
import UserAvatar from '@/components/user-avatar/user-avatar.vue'
import { Hexagram } from '@/utils/hexagram-service.js'
import { LoginService } from '@/utils/login-service.js'
import userStateManager from '@/utils/user-state-manager.js'
import apiService from '@/utils/api-service.js'

export default {
	name: 'ProfilePage',
	components: {
		GradientBackground,
		CustomNavbar,
		UserAvatar
	},
	data() {
		return {
			totalDivinations: 0,
			totalDays: 0,
			favoriteHexagram: '乾为天',
			allRecords: [],
			userInfo: {},
			isLoggedIn: false,
			loginService: null,
			userStateObserver: null,
			recommendations: [
				{
					title: '学习五行相生相克',
					desc: '了解金木水火土之间的关系，有助于更好地理解卦象含义'
				},
				{
					title: '关注起卦时机',
					desc: '选择内心平静的时刻起卦，能够获得更准确的指引'
				},
				{
					title: '记录占卜心得',
					desc: '定期回顾占卜记录，总结规律，提升解卦能力'
				}
			]
		}
	},
	computed: {
		recommendationTitle() {
			const today = new Date().getDate() % this.recommendations.length;
			return this.recommendations[today].title;
		},
		recommendationDesc() {
			const today = new Date().getDate() % this.recommendations.length;
			return this.recommendations[today].desc;
		},
		displayName() {
			return userStateManager.getDisplayName()
		},
		displayDesc() {
			return userStateManager.getDisplayDesc()
		}
	},
	onLoad() {
		this.initData();
		this.loadUserData();
		this.setupUserStateObserver();
	},
	onShow() {
		// 页面显示时重新加载数据
		this.syncUserState();
		this.loadUserData();
	},
	onUnload() {
		// 页面卸载时移除观察者
		if (this.userStateObserver) {
			userStateManager.removeObserver(this.userStateObserver)
		}
	},
	methods: {
		initData() {
			this.loginService = new LoginService()
		},
		
		setupUserStateObserver() {
			// 设置用户状态观察者
			this.userStateObserver = (type, data) => {
				console.log('用户状态变化:', type, data)
				this.syncUserState()
				if (type === 'login' || type === 'updateUserInfo') {
					this.loadUserData()
				}
			}
			userStateManager.addObserver(this.userStateObserver)
		},
		
		syncUserState() {
			// 同步用户状态
			const currentState = userStateManager.getCurrentState()
			this.isLoggedIn = currentState.isLoggedIn
			this.userInfo = currentState.userInfo || {}
		},
		
		checkLoginStatus() {
			this.loginService.checkLoginStatus()
				.then(result => {
					this.isLoggedIn = result.isLoggedIn
					if (result.isLoggedIn && result.userInfo) {
						this.userInfo = { ...this.userInfo, ...result.userInfo }
					}
				})
				.catch(error => {
					console.error('检查登录状态失败:', error)
					this.isLoggedIn = false
				})
			
			// 同时从本地存储加载用户信息
			uni.getStorage({
				key: 'user_info',
				success: (res) => {
					if (res.data) {
						this.userInfo = { ...this.userInfo, ...res.data }
					}
				}
			})
		},
		
		handleUserClick() {
			if (!this.isLoggedIn) {
				// 未登录，跳转到登录页面
				uni.navigateTo({
					url: '/pages/login/login'
				})
			} else {
				// 已登录，跳转到个人资料页面
				this.editProfile()
			}
		},
		
		editProfile() {
			if (!userStateManager.checkPermission('editProfile')) {
				uni.showToast({
					title: '请先登录',
					icon: 'none'
				})
				return
			}
			
			uni.navigateTo({
				url: '/pages/user-info/user-info'
			})
		},
		
		logout() {
			uni.showModal({
				title: '确认退出',
				content: '确定要退出登录吗？',
				success: (res) => {
					if (res.confirm) {
						// 使用全局状态管理器退出登录
						userStateManager.logout()
						uni.showToast({
							title: '已退出登录',
							icon: 'success'
						})
					}
				}
			})
		},
		
		async loadUserData() {
			if (this.isLoggedIn) {
				try {
					// 从后端API获取用户信息
					const userProfile = await apiService.getUserProfile();
					if (userProfile.success) {
						this.userInfo = { ...this.userInfo, ...userProfile.data };
						// 更新本地存储
						uni.setStorageSync('user_info', userProfile.data);
					}
					
					// 获取占卜记录
					const recordsResponse = await apiService.getDivinationRecords({
						page: 1,
						size: 100 // 获取最近100条记录用于统计
					});
					
					if (recordsResponse.success) {
						this.allRecords = recordsResponse.data.records || [];
						this.calculateStatsFromApi(recordsResponse.data);
					}
				} catch (error) {
					console.error('加载用户数据失败:', error);
					apiService.handleError(error);
					// 降级到本地数据
					this.loadLocalUserData();
				}
			} else {
				// 未登录时加载本地数据
				this.loadLocalUserData();
			}
		},
		
		loadLocalUserData() {
			// 加载本地占卜记录
			uni.getStorage({
				key: 'divination_records',
				success: (res) => {
					this.allRecords = res.data || [];
					this.calculateStats();
				},
				fail: () => {
					this.allRecords = [];
					this.calculateStats();
				}
			});
			
			// 使用全局状态管理器获取用户统计
			userStateManager.generateUserStats()
				.then(stats => {
					this.totalDivinations = stats.totalDivinations
					this.totalDays = stats.totalDays
					this.favoriteHexagram = stats.favoriteHexagram
				})
				.catch(error => {
					console.error('获取用户统计失败:', error)
				})
		},
		
		calculateStatsFromApi(apiData) {
			// 从API数据计算统计信息
			this.totalDivinations = apiData.totalCount || this.allRecords.length;
			
			// 如果API返回了统计信息，直接使用
			if (apiData.stats) {
				this.totalDays = apiData.stats.totalDays || 0;
				this.favoriteHexagram = apiData.stats.favoriteHexagram || '乾为天';
			} else {
				// 否则从记录中计算
				this.calculateStats();
			}
		},
		
		calculateStats() {
			this.totalDivinations = this.allRecords.length;
			
			// 计算使用天数
			if (this.allRecords.length > 0) {
				const firstRecord = this.allRecords[this.allRecords.length - 1];
				const lastRecord = this.allRecords[0];
				const firstDate = new Date(firstRecord.timestamp);
				const lastDate = new Date(lastRecord.timestamp);
				const diffTime = Math.abs(lastDate - firstDate);
				this.totalDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1;
			} else {
				this.totalDays = 0;
			}
			
			// 计算最常见卦象
			if (this.allRecords.length > 0) {
				const hexagramCount = {};
				this.allRecords.forEach(record => {
					const name = record.hexagram.name;
					hexagramCount[name] = (hexagramCount[name] || 0) + 1;
				});
				
				let maxCount = 0;
				let mostCommon = '乾为天';
				for (const [name, count] of Object.entries(hexagramCount)) {
					if (count > maxCount) {
						maxCount = count;
						mostCommon = name;
					}
				}
				this.favoriteHexagram = mostCommon;
			}
		},
		
		async viewMyRecords() {
			if (!userStateManager.checkPermission('viewRecords')) {
				uni.showToast({
					title: '请先登录',
					icon: 'none'
				})
				return
			}
			
			try {
				// 检查是否有记录
				const recordsResponse = await apiService.getDivinationRecords({
					page: 1,
					size: 1
				});
				
				if (recordsResponse.success && recordsResponse.data.totalCount > 0) {
					// 跳转到记录列表页面（需要创建）
					uni.navigateTo({
						url: '/pages/divination-records/divination-records'
					});
				} else {
					uni.showToast({
						title: '暂无占卜记录',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('获取记录失败:', error);
				// 降级到本地检查
				if (this.allRecords.length === 0) {
					uni.showToast({
						title: '暂无占卜记录',
						icon: 'none'
					});
				} else {
					uni.showToast({
						title: '记录管理功能开发中',
						icon: 'none'
					});
				}
			}
		},
		
		viewFavorites() {
			if (!userStateManager.checkPermission('viewFavorites')) {
				uni.showToast({
					title: '请先登录',
					icon: 'none'
				})
				return
			}
			
			uni.showToast({
				title: '收藏功能开发中',
				icon: 'none'
			});
		},
		
		openSettings() {
			uni.showModal({
				title: '设置',
				content: '设置功能开发中，敬请期待',
				showCancel: false
			});
		},
		
		openHelp() {
			uni.showModal({
				title: '帮助与反馈',
				content: '如有问题或建议，请联系我们：\n邮箱：support@mhys.com',
				showCancel: false
			});
		},
		
		openAbout() {
			uni.showModal({
				title: '关于合一个',
				content: '合一个 v1.0.0\n基于传统智慧的现代解读\n让古老的智慧指引现代生活',
				showCancel: false
			});
		},
		
		viewRecommendation() {
			uni.showModal({
				title: this.recommendationTitle,
				content: this.recommendationDesc,
				showCancel: false
			});
		}
	}
}
</script>

<style lang="scss" scoped>
.container {
	flex: 1;
	display: flex;
	flex-direction: column;
}

.content {
	flex: 1;
	padding: 32rpx;
}

.user-section {
	display: flex;
	align-items: center;
	padding: 40rpx 32rpx;
	background-color: rgba(255, 255, 255, 0.9);
	border-radius: 24rpx;
	margin-bottom: 32rpx;
	box-shadow: 0 4rpx 16rpx rgba(106, 130, 251, 0.1);
	cursor: pointer;
	transition: transform 0.2s ease;
	
	&:active {
		transform: scale(0.98);
	}
	
	.user-info {
		flex: 1;
		margin-left: 32rpx;
		
		.user-name {
			display: block;
			font-size: 36rpx;
			font-weight: 500;
			color: #000000;
			margin-bottom: 8rpx;
		}
		
		.user-desc {
			display: block;
			font-size: 28rpx;
			color: rgba(0, 0, 0, 0.7);
			margin-bottom: 8rpx;
		}
		
		.login-hint {
			.hint-text {
				font-size: 24rpx;
				color: #6A82FB;
			}
		}
	}
}

.stats-section {
	margin-bottom: 32rpx;
	
	.stats-grid {
		display: grid;
		grid-template-columns: 1fr 1fr 1fr;
		gap: 16rpx;
		
		.stats-item {
			background-color: rgba(255, 255, 255, 0.9);
			border-radius: 16rpx;
			padding: 32rpx 16rpx;
			text-align: center;
			box-shadow: 0 2rpx 8rpx rgba(106, 130, 251, 0.08);
			
			.stats-number {
				display: block;
				font-size: 32rpx;
				font-weight: bold;
				color: #6A82FB;
				margin-bottom: 8rpx;
			}
			
			.stats-label {
				display: block;
				font-size: 22rpx;
				color: rgba(0, 0, 0, 0.7);
				line-height: 1.2;
			}
		}
	}
}

.menu-section {
	margin-bottom: 32rpx;
	
	.menu-item {
		display: flex;
		align-items: center;
		padding: 32rpx;
		background-color: rgba(255, 255, 255, 0.9);
		border-radius: 16rpx;
		margin-bottom: 12rpx;
		box-shadow: 0 2rpx 8rpx rgba(106, 130, 251, 0.08);
		transition: transform 0.2s ease;
		
		&:active {
			transform: scale(0.98);
		}
		
		&:last-child {
			margin-bottom: 0;
		}
		
		.menu-icon {
			font-size: 40rpx;
			margin-right: 24rpx;
		}
		
		.menu-title {
			flex: 1;
			font-size: 30rpx;
			color: #000000;
		}
		
		.menu-arrow {
			color: rgba(0, 0, 0, 0.7);
			font-size: 24rpx;
		}
		
		&.logout-item {
			background-color: rgba(252, 92, 125, 0.1);
			
			.menu-title {
				color: #FC5C7D;
			}
			
			.menu-arrow {
				color: #FC5C7D;
			}
		}
	}
}

.recommendation-section {
	.section-title {
		font-size: 32rpx;
		font-weight: 500;
		color: #000000;
		margin-bottom: 24rpx;
	}
	
	.recommendation-card {
		display: flex;
		align-items: center;
		padding: 32rpx;
		background: linear-gradient(135deg, #E0FFE6 0%, #C2FFD0 100%);
		border-radius: 20rpx;
		transition: transform 0.2s ease;
		
		&:active {
			transform: scale(0.98);
		}
		
		.recommendation-content {
			flex: 1;
			
			.recommendation-title {
				display: block;
				font-size: 30rpx;
				font-weight: 500;
				color: #000000;
				margin-bottom: 8rpx;
			}
			
			.recommendation-desc {
				display: block;
				font-size: 26rpx;
				color: rgba(0, 0, 0, 0.7);
				line-height: 1.4;
			}
		}
		
		.recommendation-icon {
			font-size: 48rpx;
			margin-left: 20rpx;
		}
	}
}
</style>